#!/bin/bash

# ============================================
# Web3管理平台 - 实时监控面板
# ============================================

readonly GREEN='\033[0;32m'
readonly RED='\033[0;31m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly NC='\033[0m'

# 获取系统信息
get_system_info() {
    local uptime=$(uptime -p 2>/dev/null || echo "未知")
    local load=$(uptime | awk -F'load average:' '{print $2}' | xargs)
    local memory=$(free -h | awk '/^Mem:/ {print $3"/"$2}')
    local disk=$(df -h . | tail -1 | awk '{print $3"/"$2" ("$5")"}')

    echo -e "${CYAN}系统概览:${NC}"
    echo "  运行时间: $uptime"
    echo "  系统负载: $load"
    echo "  内存使用: $memory"
    echo "  磁盘使用: $disk"
}

# 获取服务状态
get_service_status() {
    echo ""
    echo -e "${CYAN}服务状态:${NC}"

    local services=("web3-mysql:MySQL" "web3-redis:Redis" "web3-backend:后端" "web3-frontend:前端")

    for service_info in "${services[@]}"; do
        local container=$(echo $service_info | cut -d':' -f1)
        local name=$(echo $service_info | cut -d':' -f2)

        if docker ps --format "{{.Names}}" | grep -q "^$container$"; then
            local status="${GREEN}●${NC} 运行中"
            local uptime=$(docker ps --format "{{.Status}}" --filter "name=$container")
        else
            local status="${RED}●${NC} 已停止"
            local uptime="未运行"
        fi

        printf "  %-8s %s (%s)\n" "$name" "$status" "$uptime"
    done
}

# 获取应用指标
get_app_metrics() {
    echo ""
    echo -e "${CYAN}应用指标:${NC}"

    # 后端健康检查
    local backend_health=$(curl -s http://localhost:8080/actuator/health 2>/dev/null)
    if [[ -n "$backend_health" ]]; then
        local status=$(echo $backend_health | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
        local color=$([[ "$status" == "UP" ]] && echo $GREEN || echo $RED)
        echo -e "  后端健康: ${color}$status${NC}"

        # 获取JVM信息
        local jvm_info=$(curl -s http://localhost:8080/actuator/metrics/jvm.memory.used 2>/dev/null)
        if [[ -n "$jvm_info" ]]; then
            local jvm_memory=$(echo $jvm_info | grep -o '"value":[0-9]*' | cut -d':' -f2)
            echo "  JVM内存: $((jvm_memory / 1024 / 1024))MB"
        fi
    else
        echo -e "  后端健康: ${RED}无响应${NC}"
    fi

    # 数据库连接数
    local db_connections=$(docker exec web3-mysql mysql -u root -p$MYSQL_ROOT_PASSWORD web3_management -e "SHOW STATUS LIKE 'Threads_connected';" 2>/dev/null | tail -1 | awk '{print $2}' || echo "0")
    echo "  数据库连接: $db_connections"

    # Redis内存使用
    local redis_memory=$(docker exec web3-redis redis-cli info memory 2>/dev/null | grep used_memory_human | cut -d':' -f2 | tr -d '\r' || echo "未知")
    echo "  Redis内存: $redis_memory"
}

# 获取客户端状态
get_client_status() {
    echo ""
    echo -e "${CYAN}客户端状态:${NC}"

    # 通过API获取客户端状态
    local client_status=$(curl -s http://localhost:8080/api/accounts 2>/dev/null)
    if [[ -n "$client_status" ]]; then
        echo "  在线客户端: $(echo $client_status | grep -o '"status":1' | wc -l)"
        echo "  总计账号: $(echo $client_status | grep -o '"id":[0-9]*' | wc -l)"
    else
        echo "  状态: 无法获取"
    fi
}

# 实时日志预览
get_recent_logs() {
    echo ""
    echo -e "${CYAN}最近日志:${NC}"

    local log_files=("web3-backend" "web3-mysql")
    for container in "${log_files[@]}"; do
        echo "  [$container]"
        docker logs --tail 2 $container 2>/dev/null | sed 's/^/    /' || echo "    无日志"
    done
}

# 主面板循环
show_realtime_dashboard() {
    while true; do
        clear

        # 标题
        echo -e "${BLUE}"
        echo "╔════════════════════════════════════════════════════════════╗"
        echo "║                Web3管理平台 - 实时监控面板                ║"
        echo "║                  $(date '+%Y-%m-%d %H:%M:%S')                  ║"
        echo "╚════════════════════════════════════════════════════════════╝"
        echo -e "${NC}"

        # 快速访问信息
        echo -e "${YELLOW}🌐 快速访问:${NC}"
        echo "  管理界面: http://$(hostname -I | awk '{print $1}'):80"
        echo "  API文档:  http://$(hostname -I | awk '{print $1}'):8080/doc.html"

        # 系统信息
        get_system_info

        # 服务状态
        get_service_status

        # 应用指标
        get_app_metrics

        # 客户端状态
        get_client_status

        # 最近日志
        get_recent_logs

        echo ""
        echo -e "${CYAN}操作提示:${NC}"
        echo "  Ctrl+C: 退出监控"
        echo "  r: 重启服务"
        echo "  l: 查看完整日志"
        echo "  u: 检查更新"

        # 非阻塞输入检测
        if read -t 5 -n 1 input 2>/dev/null; then
            case $input in
                'r'|'R')
                    echo ""
                    echo "🔄 重启服务..."
                    docker-compose restart
                    sleep 2
                    ;;
                'l'|'L')
                    echo ""
                    docker-compose logs -f
                    ;;
                'u'|'U')
                    echo ""
                    ./update.sh --auto-check
                    sleep 2
                    ;;
            esac
        fi
    done
}

# 主函数
main() {
    case ${1:-dashboard} in
        --install-monitor)
            # 安装为系统服务
            sudo tee /etc/systemd/system/web3-monitor.service > /dev/null << EOF
[Unit]
Description=Web3管理平台监控
After=docker.service

[Service]
Type=simple
User=web3
WorkingDirectory=./web3-management
ExecStart=./web3-management/monitor.sh --daemon
Restart=always

[Install]
WantedBy=multi-user.target
EOF
            sudo systemctl enable web3-monitor
            echo "✅ 监控服务已安装"
            ;;
        --daemon)
            # 后台监控模式
            while true; do
                performance_monitor > /tmp/web3-monitor.log
                sleep 60
            done
            ;;
        dashboard|*)
            show_realtime_dashboard
            ;;
    esac
}

# 信号处理
trap 'echo -e "\n👋 监控已退出"; exit 0' INT TERM

main "$@"
